package com.manong.web.intercptor;

import com.alibaba.fastjson.JSON;
import com.manong.constant.RedisConstant;
import com.manong.util.JsonResult;
import com.manong.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CheckLoginIntercptor implements HandlerInterceptor {
    @Autowired
    private RedisUtils redisUtils;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果是 OPTIONS 请求，直接放行
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        // 指定数据响应格式
        response.setContentType("application/json;charset=utf-8");
        // 1、通过request对象获取head userID
        String userId = request.getHeader("userId");
        // 2、上redis中去查询数据
        String objJson = redisUtils.get(RedisConstant.LOGIN_USER_INFO + userId);
        // 3、如果数据为空 响应401
        if(StringUtils.isEmpty(objJson)) {
            // 利用response去做响应
            JsonResult result = new JsonResult(401, "操作失败", "fail", null);
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }
        // 4、如果不为空给放行
        return true;
    }
}
